# -*- coding: utf-8 -*-
from pyes import *

INDEX_NAME = 'huxiuspider'
class SearchIndex(object):
    '''ElasticSearch建立索引的类'''

    def SearchInit(self):
        # Connect to ES
        self.conn = ES('127.0.0.1:9200', timeout = 3.5)
        try:
            self.conn.indices.delete_index(INDEX_NAME)
        except:
            pass
        # Create a new INDEX
        self.conn.indices.create_index(INDEX_NAME)

        #Define the structure of the data format
        mapping = {'content': {'boost': 1.0,
                            'index': 'analyzed',
                            'store': 'yes',
                            'type': 'string',
                            "analyzer":"ik",
                            "search_analyzer":"ik",
                            "term_vector" : "with_positions_offsets"},
                    'title': {'boost': 1.0,
                            'index': 'analyzed',
                            'store': 'yes',
                            'type': 'string',
                            "analyzer":"ik",
                            "search_analyzer":"ik",
                            "term_vector" : "with_positions_offsets"},
                    'link': {'boost': 1.0,
                            'index': 'analyzed',
                            'store': 'yes',
                            'type': 'string',
                            "term_vector" : "with_positions_offsets"},
        }

        # Define the type
        self.conn.indices.put_mapping("searchEngine-type", {'properties':mapping}, [INDEX_NAME])

    def AddIndex(self, item):
        print('Adding Index item URL %s'% item['title'])
        self.conn.index({'title':item['title'],
            'link':item['link'],
            'content':item['content']
            },INDEX_NAME,'searchEngine-type')

    def IndexDone(self):
        #Set the default indices
        self.conn.default_indices=[INDEX_NAME]
        #Refresh the ES
        self.conn.indices.refresh()
